
//

import UIKit

class HomeTableViewController: BaseTableViewController {
    var statuses: Array<Status>? {
        didSet{
            tableView.reloadData()
        }
    }
    
    var isUpRefresh: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 判断是否登陆
        if !isLogin {
            visitorView?.setupVisitorInfo(true, homeIconName: "visitordiscover_feed_image_house", messageText: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        // 设置导航内容
        setupNav()
        
        refreshControl = UIRefreshControl()
        
        refreshControl?.addTarget(self, action: #selector(HomeTableViewController.refresh), forControlEvents: UIControlEvents.ValueChanged)
        
        refreshControl?.beginRefreshing()
        self.refresh()
        
        
        
        // 设置tableView属性
        tableView.registerClass(StatusOriginalCell.self, forCellReuseIdentifier: StatusCellIdentifier.OriginalCell.rawValue)
        tableView.registerClass(StatusRetweetCell.self, forCellReuseIdentifier: StatusCellIdentifier.RetweetCell.rawValue)
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    private func setupNav() -> Void {
        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightItemClick))
        
        let titleBtn: TitleButton = TitleButton()
        titleBtn.setTitle("梁梁梁 ", forState: UIControlState.Normal)
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
        
        // 发送首页按钮点击通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changeTitleBtnImg), name: PopoverViewWillShowNotfication, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changeTitleBtnImg), name: PopoverViewWillDissmissNotfication, object: nil)
        
    }
    
    // MARK: - 事件处理
    func refresh() {
        
        
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        if isUpRefresh == true {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
            
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (models, error) in
            self.refreshControl?.endRefreshing()
            if error != nil {
                return
            }
            
            if since_id > 0 {
                self.statuses = models! + self.statuses!
                self.tipNewStatuses(models!.count)
            } else if (max_id > 0) {
                self.statuses = self.statuses! + models!
            } else {
                self.statuses = models
                self.tipNewStatuses(models!.count)
            }
            
        }
    }
    
    private func tipNewStatuses(count: Int) {
        
        if count == 0 {
            tipLabel.text = "当前无新微博"
        } else {
            tipLabel.text = "\(count)条新微博"
        }
        
        UIView.animateWithDuration(0.5, animations: {
            self.tipLabel.alpha = 1
            }) { (_) in
                UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                    self.tipLabel.alpha = 0
                    }, completion: nil)
        }
    }
    
    func changeTitleBtnImg() -> Void {
        let titleBtn = navigationItem.titleView as! TitleButton
        titleBtn.selected = !titleBtn.selected
    }
    
    func titleBtnClick(titleBtn: TitleButton) -> () {
        
        let vc = UIStoryboard(name: "Popover", bundle: nil).instantiateInitialViewController()
        vc?.transitioningDelegate = popoverAnimator;
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    func leftItemClick() -> () {
        print(#function)
    }
    
    func rightItemClick() -> () {
        let QRVC = UIStoryboard(name: "QRCode", bundle: nil).instantiateInitialViewController()
        presentViewController(QRVC!, animated: true, completion: nil)
    }
    
    private lazy var popoverAnimator: PopoverAnimator = {
       let popoverAnimator = PopoverAnimator()
        return popoverAnimator
    }()
    
    private lazy var tipLabel: UILabel = {
       let label = UILabel.label(UIColor.whiteColor(), fontSize: 15)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        label.alpha = 0
        label.frame = CGRectMake(0, 44, screenW, 30)
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}


extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status)) as! StatusCell
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let statusCell = cell as! StatusCell
        statusCell.status = statuses![indexPath.row]
        
        let index = (statuses?.count)! - 1
        if index == indexPath.row {
            isUpRefresh = true
            refresh()
        } else {
            isUpRefresh = false
        }
    }
    
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellID(status)) as! StatusCell
        
        if status.rowH == 0 {
            status.rowH = cell.cellHeight(status)
        }
        return status.rowH
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}




